<template>
  <!-- 导入表 -->
  <el-dialog v-model="visible" append-to-body title="导入表" top="5vh" width="1100px">
    <el-form ref="queryFormRef" :inline="true" :model="queryParams">
      <el-form-item label="数据源" prop="dataName">
        <el-select v-model="queryParams.dataName" clearable filterable placeholder="请选择/输入数据源名称"
                   style="width: 200px">
          <el-option key="" label="全部" value=""/>
          <el-option v-for="item in dataNameList" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="表名称" prop="tableName">
        <el-input v-model="queryParams.tableName" clearable placeholder="请输入表名称" style="width: 200px"
                  @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="表描述" prop="tableComment">
        <el-input v-model="queryParams.tableComment" clearable placeholder="请输入表描述" style="width: 200px"
                  @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
          v-model="dateRange"
          end-placeholder="结束日期"
          range-separator="-"
          start-placeholder="开始日期"
          type="daterange"
          value-format="YYYY-MM-DD"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
      <br>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>当前选中表</span>
        </div>
        <div class="text item">
          <el-tag v-text="tables?.tableName"/>
          -
          <el-tag v-text="tables?.tableComment"/>

        </div>
      </el-card>

    </el-form>
    <el-row>
      <el-table ref="tableRef" :data="dbTableList" height="260px" highlight-current-row
                @row-click="clickRow" @current-change="handleSelectionChange">

        <el-table-column align="center" label="序号" type="index" width="50">
          <template #default="scope">
            <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" align="center" label="数据源" prop="dataName"/>
        <el-table-column :show-overflow-tooltip="true" align="center" label="表名称" prop="tableName"/>
        <el-table-column :show-overflow-tooltip="true" align="center" label="表描述" prop="tableComment"/>
        <el-table-column :show-overflow-tooltip="true" align="center" label="实体" prop="className"/>
        <el-table-column align="center" label="创建时间" prop="createTime" width="160"/>
        <el-table-column align="center" label="更新时间" prop="updateTime" width="160"/>
      </el-table>
      <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                  :total="total" @pagination="getList"/>
    </el-row>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleImportTable">确 定</el-button>
        <el-button @click="visible = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 添加或修改代码生成业务2sql对话框 -->
  <el-dialog v-model="dialog2.visible" :title="dialog2.title" append-to-body width="500px">
    <el-form ref="sqlGenTableFormRef2" :model="form2" :rules="rules2" label-width="80px">

      <el-form-item label="业务名称" prop="sqlName">
        <el-input v-model="form2.sqlName" placeholder="请输入业务名称"/>
      </el-form-item>
      <el-form-item label="请输入业务类型" prop="sqlType">
        <el-input v-model="form2.sqlType" placeholder="请输入业务类型"/>
      </el-form-item>
      <el-form-item label="业务方法名称" prop="sqlMethodName">
        <el-input v-model="form2.sqlMethodName" placeholder="请输入业务方法名称"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {getDataNames, listTable} from '@/api/tool/gen2';
import {TableQuery, TableVO} from '@/api/tool/gen2/types';
import {SqlGenTableForm, SqlGenTableQuery} from "@/api/srv/sqlGenTable/types";
import {addSqlGenTable, updateSqlGenTable} from "@/api/srv/sqlGenTable";

const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const visible = ref(false);
const tables = ref<TableVO>();
const dbTableList = ref<Array<TableVO>>([]);
const {proxy} = getCurrentInstance() as ComponentInternalInstance;

const tableRef = ref<ElTableInstance>();
const queryFormRef = ref<ElFormInstance>();

const queryParams = ref<TableQuery>({
  pageNum: 1,
  pageSize: 10,
  dataName: '',
  tableName: '',
  tableComment: ''
});
const dataNameList = ref<Array<string>>([]);

const emit = defineEmits(["ok"]);

/** 单击选择行 */
const clickRow = (row: TableVO) => {
  tableRef.value?.setCurrentRow(row);
  tables.value = row;
}
/** 多选框选中数据 */
const handleSelectionChange = (selection: TableVO) => {
  tables.value = selection;
}
/** 查询表数据 */
const getList = async () => {
  const res = await listTable(proxy?.addDateRange(queryParams.value, dateRange.value));
  dbTableList.value = res.rows;
  total.value = res.total;
  visible.value = true;
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
}
/** 导入按钮操作 */
const handleImportTable = async () => {
  if (!tables.value?.tableName) {
    proxy?.$modal.msgError("请选择要导入的表");
    return;
  }
  form2.value.tableId = tables.value?.tableId;
  form2.value.dataName = tables.value?.dataName;
  form2.value.tableName = tables.value?.tableName;
  form2.value.tableComment = tables.value?.tableComment;
  form2.value.subTableName = tables.value?.subTableName;
  form2.value.subTableFkName = tables.value?.subTableFkName;
  form2.value.className = tables.value?.className;
  form2.value.tplCategory = tables.value?.tplCategory;
  form2.value.packageName = tables.value?.packageName;
  form2.value.moduleName = tables.value?.moduleName;
  form2.value.businessName = tables.value?.businessName;
  form2.value.functionName = tables.value?.functionName;
  form2.value.functionAuthor = tables.value?.functionAuthor;
  form2.value.genType = tables.value?.genType;
  form2.value.sqlType = undefined;
  form2.value.sqlName = undefined;
  form2.value.sqlMethodName = undefined;
  form2.value.genPath = tables.value?.genPath;
  form2.value.options = tables.value?.options;
  form2.value.remark = tables.value?.remark;
  dialog2.visible = true;
}
/** 查询多数据源名称 */
const getDataNameList = async () => {
  const res = await getDataNames()
  dataNameList.value = res.data;
}

const route = useRoute();
const uniqueId = ref("");
onActivated(() => {
  const time = route.query.t;
  if (time != null && time != uniqueId.value) {
    uniqueId.value = time as string;
    queryParams.value.pageNum = Number(route.query.pageNum);
    dateRange.value = ['', ''];
    queryFormRef.value?.resetFields();
    getList();
  }
})
const dialog2 = reactive<DialogOption>({
  visible: false,
  title: '请输入业务参数'
});
const sqlGenTableFormRef2 = ref<ElFormInstance>();
const initFormData: SqlGenTableForm = {
  tableId: undefined,
  dataName: undefined,
  tableName: undefined,
  tableComment: undefined,
  subTableName: undefined,
  subTableFkName: undefined,
  className: undefined,
  tplCategory: undefined,
  packageName: undefined,
  moduleName: undefined,
  businessName: undefined,
  functionName: undefined,
  functionAuthor: undefined,
  genType: undefined,
  sqlType: undefined,
  sqlName: undefined,
  sqlMethodName: undefined,
  genPath: undefined,
  options: undefined,
  remark: undefined
}
const data = reactive<PageData2<SqlGenTableForm, SqlGenTableQuery>>({
  form2: {...initFormData},
  queryParams2: {
    pageNum: 1,
    pageSize: 10,
    id: undefined,
    tableId: undefined,
    dataName: undefined,
    tableName: undefined,
    tableComment: undefined,
    subTableName: undefined,
    subTableFkName: undefined,
    className: undefined,
    tplCategory: undefined,
    packageName: undefined,
    moduleName: undefined,
    businessName: undefined,
    functionName: undefined,
    functionAuthor: undefined,
    genType: undefined,
    sqlType: undefined,
    sqlName: undefined,
    sqlMethodName: undefined,
    genPath: undefined,
    options: undefined,
    params: {}
  },
  rules2: {
    tableId: [
      {required: true, message: "编号不能为空", trigger: "blur"}
    ],
    dataName: [
      {required: true, message: "数据源名称不能为空", trigger: "blur"}
    ],
    tableName: [
      {required: true, message: "表名称不能为空", trigger: "blur"}
    ],
    tableComment: [
      {required: true, message: "表描述不能为空", trigger: "blur"}
    ],
    className: [
      {required: true, message: "实体类名称不能为空", trigger: "blur"}
    ],
    genType: [
      {required: true, message: "生成代码方式不能为空", trigger: "change"}
    ],
    sqlType: [
      {required: true, message: "生成代码方式不能为空", trigger: "change"}
    ],
    sqlName: [
      {required: true, message: "业务名称不能为空", trigger: "blur"}
    ],
    sqlMethodName: [
      {required: true, message: "业务方法名称不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams2, form2, rules2} = toRefs(data);
const buttonLoading = ref(false);
/** 提交按钮 */
const submitForm = () => {
  debugger
  sqlGenTableFormRef2.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      let res;
      if (form2.value.id) {
        res = await updateSqlGenTable(form2.value).finally(() => buttonLoading.value = false);
      } else {
        res = await addSqlGenTable(form2.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      proxy?.$modal.msgSuccess(res.msg);
      if (res.code === 200) {
        dialog2.visible = false;
        emit("ok");
      }
    }
  });
}
defineExpose({
  getList,
  getDataNameList,
});
</script>
